package com.easybuy.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.easybuy.pojo.Product;
import com.easybuy.service.ProductService;
import com.easybuy.pojo.PageBean;

@Controller
@RequestMapping("/home")
public class ProductController {
	@Resource
	ProductService productService;
	
	@RequestMapping("/floor")
	@ResponseBody
	public List<Product> select(){
		List<Product> list = productService.selectProducts();
		return list;
	}
	
	@RequestMapping("/product")
	@ResponseBody
	public Product selectProduct(@RequestParam(required = false) String id){
		if (id!=null && id!="") {
			return productService.selectProductsById(Integer.parseInt(id));
		}
		return null;
	}
	
	@RequestMapping("/productsPage")
	@ResponseBody
	public PageBean<Product> selectPage(@RequestParam(required = false) String pageNow,
			@RequestParam(required = false) String categoryLevel1Id,
			@RequestParam(required = false) String categoryLevel2Id,
			@RequestParam(required = false) String categoryLevel3Id,
			@RequestParam(required = false) String name,
			@RequestParam(required = false) String order){
		Map<String, Object> map = new HashMap<String, Object>();
		PageBean<Product> pageBean = new PageBean<Product>();
		if (pageNow==null || pageNow=="") {
			pageNow="1";
		}
		if (categoryLevel1Id!=null && categoryLevel1Id!="") {
			map.put("categoryLevel1Id", categoryLevel1Id);
		}
		if (categoryLevel2Id!=null && categoryLevel2Id!="") {
			map.put("categoryLevel2Id", categoryLevel2Id);
		}
		if (categoryLevel3Id!=null && categoryLevel3Id!="") {
			map.put("categoryLevel3Id", categoryLevel3Id);
		}
		if (name!=null && name!="") {
			map.put("name", name);
		}
		
		pageBean.setCount(productService.getCount(map));
		pageBean.setPageNow(Integer.parseInt(pageNow));
		map.put("page", pageBean);	
		
		if (order!=null && order!="") {
			if (Integer.parseInt(order)==1) {
				List<Product> list = productService.priceASC(map);
				pageBean.setList(list);
			}else if (Integer.parseInt(order)==2) {
				List<Product> list = productService.priceDESC(map);
				pageBean.setList(list);
			}
		}else {
			List<Product> list = productService.selectProductsByPage(map);
			pageBean.setList(list);
		}
		return pageBean;
	}
	
	@RequestMapping("/orderByPrice")
	@ResponseBody
	public List<Product> selectPrice(){
		List<Product> list = productService.selectOrderByPrice();
		return list;
	}
	
	@RequestMapping("/orderByStock")
	@ResponseBody
	public List<Product> selectStock(){
		List<Product> list = productService.selectOrderByStock();
		return list;
	}
}
